<template>
	<view>
		<view class="od-banner">
			<image class="od-banner-icon" src="../../static/images/od_bg_icon.png" mode="widthFix" />
			<view class="od-jd od-jd-0">
				<view class="od-jd-out">
					<view class="od-jd-in"></view>
				</view>
				<view class="vp-flex od-jd-text">
					<view class="vp-flex_1">
						<text class="od-jd-st-0">填写订单</text>
					</view>
					<view class="vp-flex_1">
						<text class="od-jd-st-10">等待陪诊</text>
					</view>
					<view class="vp-flex_1">
						<text class="od-jd-st-20">等待接单</text>
					</view>
					<view class="vp-flex_1">
						<text class="od-jd-st-30">服务进行</text>
					</view>
					<view class="vp-flex_1">
						<text class="od-jd-st-40">服务完成</text>
					</view>
				</view>
			</view>
		</view>
		<view class="pub-box">
			<view class="pub-box-bd">
				<view class="weui-cell weui-cell_input">
					<view class="weui-cell__hd">
						<image class="serv-icon"
							:src="escort.avatar ? escort.avatar : '../../static/images/avatar.jpg'">
						</image>
					</view>
					<view class="weui-cell__bd">
						<text class="serv-name">{{ escort.name }}</text>
					</view>

				</view>
			</view>
		</view>
		<block v-if="stype == '1' || stype == '2'">
			<view class="pub-box">
				<view class="pub-box-bd">
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">就诊医院</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<picker @change="onHospitalChange" :value="hospital_index" :range="hospitals"
									range-key="hospitalName">
									<input type="text" :disabled="true" placeholder="请选择要就诊的医院"
										:value="hospitals[hospital_index].hospitalName"
										placeholder-class="vp-placeholder" />
								</picker>
							</view>
						</view>
					</view>
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">服务类型</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<picker @change="onTypeChange" :value="service_index" :range="service"
									range-key="typeName">
									<input type="text" :disabled="true" placeholder="请选择预约的服务"
										:value="service[service_index].typeName" placeholder-class="vp-placeholder" />
								</picker>
							</view>
						</view>
					</view>
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">就诊时间</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<dtPicker @dtPickerChanged="onStartTimeChanged" :timestamp="order.orderStartTime"
									placeholder="请选择就诊时间"></dtPicker>
							</view>
						</view>
					</view>
					<view class="weui-cell weui-cell_input" @click="onClientChange">
						<view class="weui-cell__hd">
							<view class="weui-label">就诊人</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<input class="weui-input" placeholder-class="vp-placeholder" placeholder="请选择就诊人"
									style="text-align: right;" :disabled="true" :value="client.patientName" type="text">
							</view>
						</view>
					</view>

					<!-- 接送陪诊 —— 需要直接由用户选择地址，不用选择就诊人 -->
					<block v-if="stype == 2">
						<view class="weui-cell weui-cell_input">
							<view class="weui-cell__hd">接送地址</view>
							<view class="weui-cell__bd">
								<input class="weui-input" name="receiveAddress" style="text-align: right"
									placeholder-class="vp-placeholder" placeholder="请填写就诊人所在地址"
									v-model="order.receiveAddress" />
							</view>
						</view>
					</block>

					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">联系电话</view>
						<view class="weui-cell__bd">
							<input class="weui-input" type="number" name="tel" style="text-align: right"
								placeholder-class="vp-placeholder" placeholder="请填写您的联系电话" v-model="order.tel" />
						</view>
					</view>
				</view>
			</view>
			<view class="pub-box">
				<view class="pub-box-tt">服务需求</view>
				<view class="pub-box-bd">
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__bd">
							<textarea name="demand" auto-height placeholder="请简单描述您要就诊的科室,不清楚可不填写..."
								placeholder-class="vp-placeholder" style="min-height: 150rpx" v-model="order.demand" />
						</view>
					</view>
				</view>
			</view>

		</block>
		<block v-if="stype == 3 || stype == 4">
			<!-- 送取结果,代跑取药 -->
			<view class="pub-box">
				<view class="pub-box-bd">
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">所在医院</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<picker @change="onHospitalChange" :value="hospital_index" :range="hospitals"
									range-key="hospitalName">
									<input type="text" :disabled="true" placeholder="请选择就诊所在医院"
										:value="hospitals[hospital_index].hospitalName"
										placeholder-class="vp-placeholder" />
								</picker>
							</view>
						</view>
					</view>

					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">服务时间</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
								<dtPicker @dtPickerChanged="onStartTimeChanged" :timestamp="order.orderStartTime"
									placeholder="请选择期望服务时间"></dtPicker>
							</view>
						</view>
					</view>

					<view class="weui-cell weui-cell_input" @click="onAddressChange">
						<view class="weui-cell__hd">
							<view class="weui-label">收件信息</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<input class="weui-input" :disabled="true" style="text-align: right"
								placeholder-class="vp-placeholder" placeholder="请选择收件信息" :value="
		                                                            order.addres ? order.address : ''
		                                                        " />
							<!-- {{order.address?(order.address.userName+'('+order.address.telNumber+')'):''}} -->
						</view>
					</view>
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">联系电话</view>
						<view class="weui-cell__bd">
							<input class="weui-input" type="number" name="tel" style="text-align: right"
								placeholder-class="vp-placeholder" placeholder="请填写您的联系电话" v-model="order.tel" />
						</view>
					</view>
				</view>
			</view>

			<view class="pub-box">
				<view class="pub-box-tt">服务需求</view>
				<view class="pub-box-bd">
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__bd">
							<textarea name="demand" auto-height placeholder="如有其他服务要求请在此填写.."
								placeholder-class="vp-placeholder" style="min-height: 150rpx" v-model="order.demand" />
						</view>
					</view>
				</view>
			</view>
		</block>

		<view style="height: 300rpx;"></view>
		<!-- 悬浮提交按钮 -->
		<view class="vp-foot">
			<view style="background: #ffffff; padding: 20rpx;">
				<view class="xieyi" style="text-align: center">
					<text :class="'is_xieyi ' + (is_xieyi ? 'is_xieyi_on' : '')" @click="onXieyiChange">我已阅读并同意</text>
					<navigator :url="cfg.page_xy">《用户协议》</navigator>
					<text>和</text>
					<navigator :url="cfg.page_fw">《服务协议》</navigator>
				</view>
				<view>
					<button :class="'btnp ' + (is_xieyi ? '' : 'btnp-disabled')" @click="submit">
						确认下单
						<block v-if="order.orderPrice > 0">(支付{{ order.orderPrice }}元)</block>
					</button>
				</view>
			</view>
		</view>
	</view>

</template>

<script setup>
	import {
		h,
		reactive,
		ref,
		toRaw
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import UQRCode from 'uqrcodejs';
	const app = getApp();

	// 类别列表
	const service = ref([]);
	// 选中的类别
	const service_index = ref(0);
	// 陪诊员信息
	const escort = ref({});

	onLoad((options) => {
		console.log('options', options);
		mainLoad(options);
	});

	const token = uni.getStorageSync("token");

	// 医院列表
	const hospitals = ref([]);
	// 选中的医院
	const hospital_index = ref(0);

	const stype = ref();

	// 订单信息
	const order = reactive({
		"escortId": 0,
		"orderEndTime": "",
		"orderStartTime": "",
		"patientInfoId": 0,
		"orderPrice": 0.00,
		"typeId": 2,
		"address": "",
		"demand": "",
		"extendedPrice": 0.0,
		"hospitalId": 3,
		"hospitalName": "",
		"receiveAddress": "",
		"tel": "",
		"client": {
			"patientName": "",
			"age": 0,
			"patientPhone": "",
			"sex": 0,
			"address": ""
		}
	});

	const mainLoad = (options) => {

		console.log("token:", token);
		if (options.stype) {
			console.log("stype", options.stype);
			stype.value = options.stype;
		}

		// 医院列表
		app.globalData.utils.myrequest({
			myurl: '/hospitalInfo/list',
			mysuccess: (res) => {
				hospitals.value = res.data;

				// 服务类别列表
				app.globalData.utils.myrequest({
					myurl: '/type/list',
					data: {
						type: 1
					},
					header: {
						'Authorization': token,
						'Source-Platform': 'mini-program'
					},
					mysuccess: (res) => {
						service.value = res.data;

						// 确保医院列表已加载
						if (hospitals.value.length > 0) {
							hospital_index.value = hospitals.value.findIndex((item) => {
								console.log("hospital_index:", hospital_index);
								return item.id == options.hid;
							});

							// 如果没有找到匹配的医院，默认选择第一个
							if (hospital_index.value === -1) {
								hospital_index.value = 0;
							}

							// 类别信息默认填充第一个类别列表的第一个，后续下拉框选后自动更换
							if (service.value.length > 0) {
								service_index.value = 0; // 使用第一个服务项
								order.orderPrice = service.value[service_index.value]
									.typePrice;
							} else {
								console.error('No services available');
							}

							order.hospitalId = hospitals.value[hospital_index.value]
								.hospitalId;
							order.hospitalName = hospitals.value[hospital_index.value]
								.hospitalName;
							order.hospitalAddress = hospitals.value[hospital_index.value]
								.hospitalAddress;
						} else {
							console.error('No hospitals available');
						}

						// 陪诊员信息
						if (options.escort) {
							try {
								escort.value = JSON.parse(decodeURIComponent(options.escort));
								console.log("escort", escort);
								order.escortId = escort.value.id; // 陪诊员id
							} catch (error) {
								console.error('Error parsing escort:', error);
							}
						}
					},
					myfail: (error) => {
						console.log("类别接口调用失败!", error);
					}
				});
			},
			myfail: (error) => {
				console.log("医院接口调用失败!", error);
			}
		});
	};

	const onHospitalChange = (e) => {
		hospital_index.value = e.detail.value;
		order.hospitalId = hospitals.value[hospital_index.value].id;
		order.address=hospitals.value[hospital_index.value].hospitalAddress;
		order.hospitalName = hospitals.value[hospital_index.value].hospitalName;
	};

	const onTypeChange = (e) => {
		service_index.value = e.detail.value;
		order.orderPrice = service.value[service_index.value].typePrice;
		order.typeId = service.value[service_index.value].id;
	};

	// 开始时间
	const onStartTimeChanged = (obj) => {
		console.log('时间', obj);
		order.orderStartTime = obj.detail.value;
	};

	// 结束时间
	const onEndTimeChanged = (obj) => {
		order.orderEndTime = obj.detail.value;
	};

	// 就诊人
	const client = reactive({
		patientName: '',
		age: 1,
		patientPhone: '',
		sex: 0,
		address: ''
	});

	const onClientChange = () => {
		uni.navigateTo({
			url: '../clients/index?act=select'
		});
	};

	uni.$on('changeClient', (data) => {
		client.id = data.id;
		client.patientName = data.patientName;
		client.age = data.age;
		client.patientPhone = data.patientPhone;
		client.sex = data.sex;
		client.address = data.address;

		order.client.id = data.id;
		order.client.patientName = data.patientName;
		order.client.age = data.age;
		order.client.patientPhone = data.patientPhone;
		order.client.sex = data.sex;
		order.client.address = data.address;
	});

	const cfg = reactive({
		page_xy: '',
		page_fw: ''
	})

	//定义是否点击确认协议
	const is_xieyi = ref(false)
	const onXieyiChange = () => {
		is_xieyi.value = !is_xieyi.value;
	};

	const onAddressChange = () => {
		uni.chooseAddress({
			success(res) {
				console.log('成功地址', res);
				order.address.userName = res.userName
				order.address.cityName = res.cityName
				order.address.countyName = res.countyName
				order.address.detailInfo = res.detailInfo
			},
			fail(res) {
				console.log('失败地址', res);
			}
		})
	}

	//订单提交
	const submit = () => {
		if (!is_xieyi.value) {
			return uni.showToast({
				title: '请勾选协议',
				duration: 1200,
				icon: 'error'
			});
		}

		createOrder();
	};

	const createOrder = () => {
		order.patientInfoId = order.client.id;
		order.extendedPrice = 0.00;
		order.satisfactionLevel = 0;

		console.log('订单信息wwww', order);
		app.globalData.utils.myrequest({
			myurl: '/order/start',
			method: 'POST',
			data: order,
			header: {
				'Authorization': token,
				'Source-Platform': 'mini-program'
			},
			mysuccess: (res) => {
				console.log('订单提交信息', res);
				uni.showToast({
					title: '订单已提交',
					duration: 1200,
					icon: 'success'
				});
				console.log("订单保存返回数据：", res.data)
				payOrder(res.data); // 调用支付接口
			},
			myfail: (err) => {
				console.log('订单提交错误信息', err);
				return uni.showToast({
					title: '订单提交错误',
					icon: 'error'
				});
			}
		});
	};

	const payOrder = (orderCode) => {
		app.globalData.utils.myrequest({
			myurl: '/order/pay',
			method: 'GET',
			data: {
				orderCode: orderCode
			},
			header: {
				'Authorization': token,
				'Source-Platform': 'mini-program'
			},
			mysuccess: (res) => {
				console.log('订单支付信息', res);
				uni.showToast({
					title: '支付成功',
					duration: 1200,
					icon: 'success'
				});
				uni.switchTab({
					url: '../myorder/index'
				});
			},
			myfail: (err) => {
				console.log('订单支付错误信息', err);
				return uni.showToast({
					title: '支付失败',
					icon: 'error'
				});
			}
		});
	};
</script>

<style>
	@import url(./index.css);
</style>